package ch.fusun.baron.city;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import ch.fusun.baron.city.api.CityService;
import ch.fusun.baron.data.AbstractDataProvider;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.map.Tile;

/**
 * The implementation of the city service
 */
public class CityServiceImpl extends AbstractDataProvider implements
		CityService {

	private final Map<Tile, City> cityMap = new HashMap<Tile, City>();
	private int idCounter = 0;

	@Override
	public DataUpdate createFullUpdate() {
		return new CityDataUpdate(cityMap);
	}

	@Override
	public void setCity(Tile tile, City city) {
		cityMap.put(tile, city);
		updateAllListeners(new NewCityDataUpdate(tile, city));
	}

	@Override
	public City getCity(Tile model) {
		return cityMap.get(model);
	}

	@Override
	public Tile getLocation(City city) {
		for (Tile tile : cityMap.keySet()) {
			if (cityMap.get(tile).equals(city)) {
				return tile;
			}
		}
		return null;
	}

	@Override
	public void createCity(Tile tile) {
		setCity(tile, new City(idCounter++));
	}

	@Override
	public void removeCity(City city) {
		cityMap.remove(getLocation(city));
		updateAllListeners(new RemoveCityDataUpdate(city));
	}

	@Override
	public Collection<City> getCities() {
		return cityMap.values();
	}

}
